<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WtAsin;
use App\Models\WtCategory;
use App\Models\WtConfig;
use App\Models\WtOrderAsin;
use App\Models\WtOrderProduct;
use App\Models\WtAsinNotSale;
use App\Models\WtTask;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class HomeController extends Controller
{
    protected $request;
    private $insert_batch = [];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 生成keepa分类树结构
     */
    public function create_category(Request $request)
    {
        $domainId = $request->post('domainId');
        $parent_id = $request->post('catId');
        $is_all = $request->post('is_all');
        $month = $request->post('month');

        //发起请求
        $api = new \Keepa\KeepaAPI(env('KEEPA_API_KEY'));
        $this->send_keepa_api($api, $domainId, $parent_id, $month, $is_all);
        if (count($this->insert_batch)) {
            WtCategory::insert($this->insert_batch);
        }
        return Success('ok', $this->insert_batch);
    }

    public function send_keepa_api($api, $domain_id, $pid, $month, $is_all = false)
    {
        $r = \Keepa\API\Request::getCategoryLookupRequest((int)$domain_id, true, $pid);
        $response = $api->sendRequestWithRetry($r);
        if ($response->status == \Keepa\API\ResponseStatus::OK) {
            //批量插入的分类
            foreach ($response->categories as $category) {
                if ($category->children) {
                    $category->children_str = implode(',', $category->children);
                    $category->children_num = count($category->children);
                } else {
                    $category->children_num = 0;
                }

                //只获取为浏览器节点的分类
                if ($category->isBrowseNode) {
                    $this->insert_batch[] = [
                        'catId' => $category->catId,
                        'domainId' => $category->domainId,
                        'name' => $category->name,
                        'parent_id' => $category->parent,
                        'children_str' => $category->children_str,
                        'children_num' => $category->children_num,
                        'month' => $month,
                        'create_time' => time(),
                    ];
                }

                //若包含子类i，递归调用，获取所有
                if ($category->children_num > 0 && $is_all) {
                    $cat_arr = explode(',', $category->childrens);
                    $splits = array_chunk($cat_arr, 10);
                    foreach ($splits as $split) {
                        $cat_str = implode(',', $split);
                        $this->send_keepa_api($api, $domain_id, $month, $cat_str);
                    }
                }
            }
        }
    }

    public function get_company_asin()
    {
        $config = WtConfig::first();
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_ALL;
        $post = ['country' => $config->country, 'month' => $config->month];
        $response = Http::get($url, $post);
        if ($response->ok()) {
            $asins = $response->json()['data'];
            $on_sales = [];
            $no_sales = [];
            $insert = [];

            $not_sale_asin = WtAsinNotSale::where(['country' => $config->country])->get();
            foreach ($asins as $asin) {
                $on_sales[] = $asin;
            }
            foreach ($not_sale_asin as $no_asin) {
                $no_sales[] = $no_asin;
            }
            $diff = array_diff($on_sales, $no_sales);

            foreach ($diff as $item) {
                $insert[] = ['asin' => $item, 'country' => $config->country, 'month' => $config->month];
            }
            if (count($insert)) {
                $res = WtAsin::insert($insert);
                dd($res);
            } else {
                print_r('no data');
            }
        } else {
            dd($post);
        }
    }

    /**
     * 根据wt_order_product更新wt_category表中sku量、订单量、订单数
     */
    public function update_category_order()
    {
        $param = $this->request->post();
        $pipeline = [
            [
                '$match' => [
                    'month' => $param['month'],
                    'locale' => $param['locale'],
                ]
            ],
            [
                '$group' => [
                    '_id' => '$category_id',
                    'order_num' => ['$sum' => '$order_num'],
                    'order_counts' => ['$sum' => '$order_counts'],
                    'sku_count' => ['$sum' => '$sku_count'],
                ]
            ]
        ];

        $results = WtOrderProduct::aggregate($pipeline);
        var_dump(response()->json($results));

        // 准备批量更新的数据
        $bulkUpdates = [];
        // 遍历数组，准备批量更新的操作
        foreach ($results as $categoryData) {
            $categoryId = $categoryData['_id'];
            $orderTotal = $categoryData['order_num'];
            $orderCounts = $categoryData['order_counts'];
            $skuCounts = $categoryData['sku_count'];

            // 准备批量更新的操作
            $bulkUpdates[] = [
                'updateOne' => [
                    ['catId' => $categoryId],
                    ['$set' => ['order_num' => $orderTotal, 'order_counts' => $orderCounts, 'sku_count' => $skuCounts]],
                    ['upsert' => false]
                ]
            ];
        }

        // 执行批量更新操作
        WtCategory::raw(function ($collection) use ($bulkUpdates) {
            $res = $collection->bulkWrite($bulkUpdates);
            print_r($res);
        });
    }

    /**
     * 请求ceping_system获取asin的sku量、订单量、订单数保存到wt_order_asin中
     * @param Request $request
     */
    public function get_asin_order_num()
    {
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_ORDER_NUM;
        $post = WtConfig::first();

        $response = Http::get($url, $post);
        if ($response->ok()) {
            if ($response->json()['status']) {
                $insert = array();
                $res = $response->json()['result'];
                foreach ($res as $re) {
                    $insert[] = [
                        'month' => $post['month'],
                        'country' => $post['country'],
                        'asin' => $re['_id']['asin'],
                        'order_num' => $re['counts'],
                        'order_counts' => $re['quantities'],
                        'sku_count' => $re['sku_count'],
                        'group_name' => $re['group_name'],
                    ];
                }
                if (count($insert)) {
                    $where['month'] = $post['month'];
                    $where['country'] = strtoupper($post['country']);
                    $exists = WtOrderAsin::where($where)->first();
                    if (!$exists) {
                        $ret = WtOrderAsin::insert($insert);
                        dd($ret);
                    } else {
                        echo '该月已生成asin订单数据！';
                    }
                }
            } else {
                echo $response->json()['message'];
            }

        } else {
            echo '请求失败！';
        }
    }

    /**
     * 根据子分类更新其所有上级分类的sku量、订单量、订单数
     */
    public function update_wt_order_to_parent()
    {
        $pipeline = [
            [
                '$match' => [
                    'order_num' => ['$exists' => true]
                ]
            ],
            [
                '$group' => [
                    '_id' => '$parent_id',
                    'order_num_total' => ['$sum' => '$order_num'],
                    'order_count_total' => ['$sum' => '$order_counts'],
                    'sku_count_total' => ['$sum' => '$sku_count'],
                ]
            ]
        ];

        $results = WtCategory::aggregate($pipeline);

        $bulkUpdates = [];
        foreach ($results as $item) {
            $cate = WtCategory::where(['catId' => $item['_id']])->first();
            if (!isset($cate['order_num'])) {
                $bulkUpdates[] = [
                    'updateOne' => [
                        ['catId' => $item['_id']],
                        ['$set' => ['order_num' => $item['order_num_total'], 'order_counts' => $item['order_count_total'], 'sku_count' => $item['sku_count_total']]],
                        ['upsert' => false]
                    ]
                ];
            }
        }

        if (count($bulkUpdates)) {
            WtCategory::raw(function ($collection) use ($bulkUpdates) {
                $res = $collection->bulkWrite($bulkUpdates);
                print_r('有上级未更新！');
            });

            var_dump('<br />');
            $this->update_wt_order_to_parent();
        } else {
            print_r('无分类需要更新！');
        }
    }

    /**
     * 更新分类树展示名称，为分类名称+订单量等数据
     */
    public function create_name()
    {
        ini_set('memory_limit', '256M');
        $config = WtConfig::first();
        $where = ['month' => $config->month, 'domainId' => translateCountryToDomainId($config->country)];
//        $where = ['month' => $config->month];
        $documents = WtCategory::where($where)->get();

        $bulkUpdates = [];
        foreach ($documents as $document) {

            if ($document->order_num_total) {
                $new_name = $document->name . ' (' . $document->sku_count_total . ' | ' . $document->order_count_total . ') ';
            } else {
                $new_name = $document->name;
            }

            $bulkUpdates[] = [
                'updateOne' => [
                    ['catId' => $document['catId'], 'month' => $config['month'], 'domainId' => translateCountryToDomainId($config->country)],
                    ['$set' => ['new_name' => $new_name]],
                    ['upsert' => false]
                ]
            ];
            print_r('更新分类' . $document->name . '，新名称' . $new_name);
            print_r('<br />');

        }
        if (count($bulkUpdates)) {
            WtCategory::raw(function ($collection) use ($bulkUpdates) {
                $res = $collection->bulkWrite($bulkUpdates);
                print_r($res);
            });
        } else {
            print_r($config);
            print_r('无分类需要更新！');
        }
    }

    /**
     * 根据订单asin表更新订单产品详情中组名
     */
    public function update_group_name()
    {
        $results = WtOrderAsin::where(['group_name' => ['$exists' => true], 'country' => 'de'])->get();
        $bulkUpdates = [];
        foreach ($results as $item) {
            $bulkUpdates[] = [
                'updateOne' => [
                    ['asin' => $item['asin'], 'locale' => $item['country']],
                    ['$set' => ['group_name' => $item['group_name']]],
                    ['upsert' => false]
                ]
            ];
        }

        if (count($bulkUpdates)) {
            WtOrderProduct::raw(function ($collection) use ($bulkUpdates) {
                $res = $collection->bulkWrite($bulkUpdates);
                print_r($res);
            });

            var_dump('<br />');
        }
    }

    /**
     * 请求接口更新数据名
     */
    public function update_sj_name()
    {
        ini_set('memory_limit', '1024M');
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_SJ_NAME;
//        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_SJ_NAME_NEW;
        $response = Http::get($url);
        $config = WtConfig::first();
        if ($response->ok()) {
            $sj_names = $response->json()['data'];
            $bulkUpdates = [];
            foreach ($sj_names as $k => $v) {
                $bulkUpdates[] = [
                    'updateMany' => [
                        ['asin' => $k, 'month' => $config->month, 'sj_name' => ['$exists' => false]],
                        ['$set' => ['sj_name' => $v]],
                        ['upsert' => false]
                    ]
                ];
            }

            if (count($bulkUpdates)) {
                WtOrderProduct::raw(function ($collection) use ($bulkUpdates) {
                    $res = $collection->bulkWrite($bulkUpdates);
                    print_r($res);
                });

                var_dump('<br />');
            }
        } else {
            print_r($response->reason());
        }
    }

    /**
     * 复制以往月份分类数据
     */
    public function copy_category(Request $request)
    {
        $params = $request->post();
        if (!isset($params['month']) || !$params['month']) {
            print_r('请选择要复制分类的以往月份！');
            exit();
        }

        if (strtotime($params['month']) > strtotime('2024-04')) {
            print_r('仅可复制2024-04之前月份的分类数据！');
            exit();
        }

        //判断是否存在
        $exists = WtCategory::where(['month' => $params['month']])->first();
        if ($exists) {
            print_r('已存在该月份数据！');
            exit();
        }

        ini_set('memory_limit', '1024M');
        $categories = WtCategory::where(['month' => '2024-04'])->get();
        $inserts = [];
        foreach ($categories as $category) {
            $inserts[] = [
                'catId' => $category->catId,
                'domainId' => $category->domainId,
                'name' => $category->name,
                'parent_id' => $category->parent_id,
                'month' => $params['month'],
                'children_str' => $category->children_str,
                'children_num' => $category->children_num,
            ];
        }
        $re = WtCategory::insert($inserts);
        print_r($re);
    }

    /**
     * 生成分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_category(Request $request)
    {
        $post = $request->post();
        if (!$post['month']){
            Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::whereIn('category_completed',['pending', 'completed'])->first();
        if ($is_ing){
            Error($is_ing->month.'月的分类数据正在生成中或已生成完毕！');
        }

        //检测是否为2024-04月之前的历史数据生成
        $month = $post['month'];
        if (strtotime($month) < strtotime('2024-04')){
            $exists = WtCategory::where(['month' => $month])->first();
            if ($exists) {
                print_r('已存在该月份数据！');
                exit();
            }

            ini_set('memory_limit', '1024M');
            $categories = WtCategory::where(['month' => '2024-04'])->get();
            $inserts = [];
            foreach ($categories as $category) {
                $inserts[] = [
                    'catId' => $category->catId,
                    'domainId' => $category->domainId,
                    'name' => $category->name,
                    'parent_id' => $category->parent_id,
                    'month' => $month,
                    'children_str' => $category->children_str,
                    'children_num' => $category->children_num,
                ];
            }
            $re = WtCategory::insert($inserts);
            return Success('生产完毕！',$re);
        }else{
            //调用python请求keepa分类
//            $pythonScriptPath = base_path('app/python_scripts/wt_order_product_local.py'); // 脚本的完整路径
            $pythonScriptPath = 'wt_order_product_local.py';

            // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
//        $handle = popen("python {$pythonScriptPath} '{$month}' > /dev/null 2>&1 &", 'r');
            $handle = popen("start /B python {$pythonScriptPath} {$month}", 'r');

            // 检查是否成功打开进程
            if ($handle) {
                pclose($handle);
                echo 'Python script started in the background.';
            } else {
                echo 'Error: Unable to start Python script.';
            }
        }
    }

    /**
     * 请求ceping_system生成订单asin数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_order_asin(Request $request)
    {
        //该月是否已生成
        $post = $request->post();
        $where['month'] = $post['month'];
        $exists = WtOrderAsin::where($where)->first();
        if ($exists) {
            return Error('该月已生成asin订单数据');
        }

        //上一步是否完成
        $static = WtTask::where('month', $post['month'])->first();
        if ($static->category_completed !== 'completed') {
            return Error('本月分类数据尚未获取完毕！');
        }

        //请求ceping的订单数据
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_ORDER_NUM;
        $response = Http::get($url, $post);
        if ($response->ok()) {
            if ($response->json()['status']) {
                $insert = array();
                $res = $response->json()['result'];
                foreach ($res as $re) {
                    $insert[] = [
                        'month' => $post['month'],
                        'country' => strtolower($re['_id']['country']),
                        'asin' => $re['_id']['asin'],
                        'order_num' => $re['counts'],
                        'order_counts' => $re['quantities'],
                        'sku_count' => $re['sku_count'],
                        'group_name' => $re['_id']['group_name'],
                    ];
                }
                if (count($insert)) {
                    WtOrderAsin::insert($insert);
                    WtTask::where('month', $post['month'])->update(['order_asin_completed' => 'completed']);
                    return Success('获取成功',$insert);

                } else {
                    return Error('该月无asin订单数据');
                }
            } else {
                return Error($response->json()['message']);
            }

        } else {
            return Error('请求失败');
        }
    }

}
